package com.txtsqlclient.ws;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import Acme.Serve.ServeSessionManager;

import com.txtsqlclient.dataaccess.database.connection.ConnectionException;
import com.txtsqlclient.dataaccess.database.connection.ConnectionFactory;
import com.txtsqlclient.domain.DataSource;

@SuppressWarnings("serial")
public class LogoutServlet extends BaseServlet {

	private static Log LOGGER = LogFactory.getLog(LogoutServlet.class);

	@Override
	protected void processRequest(HttpServletRequest req,
			HttpServletResponse res) throws IOException {
		LOGGER.info("Request received for Logout at: "
				+ DateFormat.getDateTimeInstance().format(
						Calendar.getInstance().getTime()));
		HttpSession session = req.getSession();
		// Need to put validations.
		DataSource ds = (DataSource) session
				.getAttribute(QueryServlet.DATA_SOURCE_SESSION_VARIABLE);
		try {
			ConnectionFactory.getInstance().closeConnection(ds);
			populateResponse(req, res);
		} catch (ConnectionException e) {
			populateErrorResponse(req, res, e,
					"Error connecting to the database. Please verify the login information.");
			LOGGER.error("Error connecting to the database.", e);
		} finally {
			session.invalidate();
		}
		String dirPath = LoginServlet.TEMP_DIR_PATTERN.replace("{sessionId}",
				session.getId());
		deleteTemporaryFolder(dirPath);
	}

	protected void deleteTemporaryFolder(String dirPath) {
		File tempDir = new File(dirPath);
		if (tempDir.listFiles() != null) {
			for (File tempFile : tempDir.listFiles()) {
				tempFile.delete();
			}
		}
		tempDir.delete();
	}

	protected void populateResponse(HttpServletRequest req,
			HttpServletResponse res) throws IOException {
		res.setStatus(HttpServletResponse.SC_OK);
		res.setContentType("text/xml");
		ServletOutputStream out = res.getOutputStream();
		out
				.println("<p:LogoutResponse xmlns:p='http://code.google.com/p/txt-sql-client' "
						+ ServeSessionManager.SESSION_COOKIE_NAME
						+ "='"
						+ req.getSession().getId() + "'></p:LogoutResponse>");
		out.flush();
		out.close();
	}

	protected void populateErrorResponse(HttpServletRequest req,
			HttpServletResponse res, Throwable error, String errorMessage)
			throws IOException {
		res.setStatus(HttpServletResponse.SC_OK);
		res.setContentType("text/xml");
		ServletOutputStream out = res.getOutputStream();
		out
				.println("<p:LogoutResponse xmlns:p='http://code.google.com/p/txt-sql-client' "
						+ ServeSessionManager.SESSION_COOKIE_NAME
						+ "='"
						+ req.getSession().getId() + "'><Errors>");
		out.println("<Error>" + errorMessage + "</Error>");
		Throwable t = error;
		while (t != null) {
			out.println("<Error>" + t.getMessage() + "</Error>");
			t = t.getCause();
		}
		out.println("</Errors></p:LogoutResponse>");
		out.flush();
		out.close();
	}
}
